<template>
  <div>
    <div class="pageCard">
      <a-form layout="inline" :model="formSearch" style="align-items: center">
        <span style="font-weight: bold">当前医疗机构:</span>
        <span style="font-weight: bold; margin: 0 10px">{{
          hospitalBaseName
        }}</span>
        <a-form-item>
          <a-input
            v-model:value="formSearch.code"
            placeholder="请输入医疗机构编码"
          >
          </a-input>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="getSearch">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="toresetFields">重置</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div style="background: #fff">
      <a-table
        style="padding: 0 20px"
        :columns="columns"
          :pagination="pagination"
        :rowKey="(record) => record.id"
        :data-source="list"
        :row-selection="rowSelection"
      >
        <template #type="{ record }">
          {{ record.type == 0 ? "科室" : "分院" }}
        </template>

        <template #operation="{ record }">
          <div style="display: flex; align-items: center">
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_blue"
              @click="addHandle(record)"
            >
              添加下级单位
            </div>
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_blue"
              @click="editHandle(record)"
            >
              编辑
            </div>
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_blue"
              @click="handleGenerateQrCode(record)"
            >
              下载二维码
            </div>
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_red"
              @click="delHandle(record)"
            >
              删除
            </div>
          </div>
        </template>
        <template #title>
          <div class="ANTTable_header">
            <div style="font-weight: bold">科室信息维护</div>
            <div>
              <a-button @click="handleImport">导入</a-button>
              <a-button @click="handleDownloadCode" style="margin: 0 10px"
                >批量下载二维码</a-button
              >
              <a-button type="primary" @click="addHandle('')"
                >添加下级单位</a-button
              >
            </div>
          </div>
        </template>
      </a-table>
    </div>

    <a-modal
      width="40%"
      v-model:visible="visible"
      :title="handleTitle"
      @ok="handleOk"
      @cancel="handleCancle"
      ok-text="确认"
      cancel-text="取消"
    >
      <child
        v-if="visible"
        :handleType="handleType"
        :handleRow="handleRow.data"
        ref="child"
        @finish="finishHandle"
      ></child>
    </a-modal>

    <a-modal
      width="40%"
      v-model:visible="ImportFilevisible"
      title="导入科室"
      @ok="ImporthandleOk"
      ok-text="确认上传"
      cancel-text="取消"
    >
      <a-upload-dragger   accept="application/vnd.ms-excel" :before-upload="beforeUpload" v-model:fileList="fileList" name="file" >
        <p class="ant-upload-drag-icon">
          <inbox-outlined></inbox-outlined>
        </p>
        <a-button @click.stop="ImporthandleCancle()">下载模板</a-button>
        <p class="ant-upload-text">第一步:下载Excel科室模板;</p>
        <p class="ant-upload-text">
          第二步:使用模板编辑科室,点击"选择文件"选择您编辑好的Excel文档;
        </p>
        <p class="ant-upload-text">第三步:点击"确认上传"完成科室导入;</p>
      </a-upload-dragger>
    </a-modal>
  </div>
</template>
<script>
import child from "./components/child.vue";
import { createVNode, onMounted, reactive, ref, toRefs, watch } from "vue";
import * as utils from "@/utils/index.js";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { Form } from "ant-design-vue";
import { Modal, message } from "ant-design-vue";
import { getUserInfo } from "@/utils/auth";
import * as Auth from "@/utils/auth";
import * as hospitalDepartApi from "@/api/hospitalDepart.js";
import {
  hospitalDepartList,
  hospitalDepartRemoce,
  generateQrCode,
  generateQrCodeBatch,
} from "@/api/hospitalDepart.js";
// 表格Column
const columns = [
  {
    title: "科室名称",
    dataIndex: "name",
  },
  {
    title: "科室编码",
    dataIndex: "code",
  },
  {
    title: "科室电话",
    dataIndex: "mobile",
  },
  {
    title: "科室负责人",
    dataIndex: "userStaffName",
  },
  {
    title: "单位类型",
    dataIndex: "type",
    slots: { customRender: "type" },
  },

  {
    title: "操作",
    dataIndex: "operation",
    width: 300,
    slots: { customRender: "operation" },
  },
];
const useForm = Form.useForm;
export default {
  components: {
    child,
    ExclamationCircleOutlined,
  },
  setup(props,{emit}) {
    const hospitalBaseName = ref(
      Auth.getUserInfo() ? JSON.parse(Auth.getUserInfo()).hospitalBaseName : ""
    );
    const formSearch = reactive({
      code: "",
    });
    const userInfo = ref(getUserInfo() ? JSON.parse(getUserInfo()) : {});
    const tableData = reactive({ list: [], total: 0 });
    const { resetFields } = useForm(formSearch);
    const pageSize = ref(10);
    const pageIndex = ref(1);
     const beforeUpload = ()=>{
      return false
    }
    // 查询
    const getSearch = () => {
      handleGetDataList();
    };
    const pagination = reactive({
      total: 0,
      current:pageIndex.value,
      pageSize: pageSize.value, // 默认每页显示数量
      showSizeChanger: true, // 显示可改变每页数量
      pageSizeOptions: ["10", "20", "30", "40"], // 每页数量选项
      showTotal: (total) => `总数 ${total}条数据`, // 显示总数
      onChange: (page, size) => {
        onPageChange(page, size);
      }, // 改变每页数量时更新显示
      onShowSizeChange: (current, size) => {
        onSizeChange(current, size);
      },
    });
    // 分页
    const onSizeChange = (current, size) => {
      pageIndex.value = 1;
      pagination.current = 1
      pageSize.value = size;
      handleGetDataList();
    };
    const onPageChange = (current, size) => {
      pageIndex.value = current;
      pagination.current = current
      handleGetDataList();
    };
    // 获取表格
    const handleGetDataList = () => {
      tableData.list = [];
      let params = {
       ...formSearch,
       
      };
      hospitalDepartList(params).then((res) => {
        if (res && res.success) {
          console.log(123);
          console.log(res);
          tableData.list = utils.treeDataTranslate(res.data);
          pagination.total = res.total
        }
      });
    };
const tableSelectedRows = ref([])
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
       tableSelectedRows.value = selectedRows
      },
      onSelect: (record, selected, selectedRows) => {
        console.log(record, selected, selectedRows);
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        console.log(selected, selectedRows, changeRows);
      },
    };

    // 重置表格
    const toresetFields = () => {
      resetFields();
      getSearch();
    };
    // 监听表格
    watch(
      () => formSearch,
      (curAge, preAge) => {
        getSearch();
      },
      { deep: true }
    );

    //  新增功能
    const visible = ref(false);
    const handleType = ref("add");
    const handleTitle = ref("新增科室");
    const handleRow = reactive({ data: {} });
    const addHandle = (row) => {
      visible.value = true;
      handleType.value = "add";
      handleTitle.value = row ? "新增下级科室" : "新增科室";
      console.log(row);
      if (!row) {
        handleRow.data = {
          parentName: hospitalBaseName.value,
          parentId: "",
        };
      } else {
        handleRow.data = {
          parentName: row.name,
          parentId: row.id,
        };
      }
    };

    const editHandle = (data) => {
      visible.value = true;
      handleType.value = "edit";
      handleTitle.value = "编辑科室";
      handleRow.data = {
        ...data,
        parentName: data.parentId ? data.parentName : hospitalBaseName.value,
      };
    };
    // 删除
    const delHandle = (data) => {
      Modal.confirm({
        title: () => "提示",
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () =>
          createVNode("div", { style: "color:red;" }, "确认删除该科室"),
        onOk() {
          hospitalDepartRemoce(data.id).then((res) => {
            if (res && res.success) {
              message.success("删除成功");
              getSearch();
            }
          });
        },
        onCancel() {
          console.log("Cancel");
        },
        class: "test",
      });
    };
    //导入
    const handleImport = () => {
      ImportFilevisible.value = true;
    };
    //批量下载二维码
    const handleDownloadCode = () => {
      if( tableSelectedRows.value.length<=0){
        message.warning('请选择数据')
        return false
      }
      let params = tableSelectedRows.value.map((item) => {
        return item.id;
      });
      generateQrCodeBatch(params).then((res) => {
        const link = document.createElement("a");
        const blob = new Blob([res], {
          type: "application/zip", // "application/zip",
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = "科室"; // 下载后文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        message.success('操作成功')
      });
    };
    //下载二维码
    const handleGenerateQrCode = (row) => {
      generateQrCode(row.id).then((res) => {
        const link = document.createElement("a");
        const blob = new Blob([res], {
          type: "image/png", // "application/zip",
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = row.name; // 下载后文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    };
    // 完成操作
    const finishHandle = () => {
      visible.value = false;
      handleGetDataList();
    };

    const child = ref(null);
    const handleOk = () => {
      child.value.handleSave();
    };

    const handleCancle = () => {
      child.value.resetForm();
    };

    // 导入功能
    const ImportFilevisible = ref(false);
    const fileList = ref([]);

    const ImporthandleOk = () => {
      console.log(fileList.value[0].originFileObj);
      let formDate = new FormData();
      formDate.append("file", fileList.value[0].originFileObj);
      hospitalDepartApi.importList(formDate).then((res) => {
        if (res && res.success) {
          message.success('导入成功')
          ImportFilevisible.value = false
          handleGetDataList()
        }
      });
    };

    const ImporthandleCancle = () => {
      hospitalDepartApi.downloadTemplate().then((res) => {
        const link = document.createElement("a");
        const blob = new Blob([res], {
          type: "application/vnd.ms-excel", // "application/zip",
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = "科室"; // 下载后文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });

      return false;
    };
    onMounted(() => {
      handleGetDataList();
    });
    return {
      child, //子组件
      hospitalBaseName,
      formSearch,
      toresetFields,
      userInfo,
      columns,
      ...toRefs(tableData),
      handleGetDataList,
      getSearch,
      pagination,
      visible,
      addHandle,
      editHandle,
      handleTitle,
      handleRow,
      handleType,
      handleOk,
      handleCancle,
      finishHandle,

      delHandle,
      handleGenerateQrCode,
      handleDownloadCode,

      ImportFilevisible,
      fileList,
      ImporthandleOk,
      ImporthandleCancle,
      handleImport,
      rowSelection,
      tableSelectedRows,
      beforeUpload
    };
  },
};
</script>